﻿using RuneMasterWin8.Core;
using RuneMasterWin8.Entities;
using RuneMasterWin8.Entities.GameRecord;
using RuneMasterWin8.Util;
using RuneMasterWin8.Views;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234237 上有介绍

namespace RuneMasterWin8.Pages
{
    /// <summary>
    /// 基本页，提供大多数应用程序通用的特性。
    /// </summary>
    public sealed partial class GamePage : RuneMasterWin8.Common.LayoutAwarePage
    {
        public static GamePage Instance;

        int currentScore = 0;
        int currentSprite = 0;
        int currentSumCombo = 0;
        StageInfo currentStageInfo = null;

        List<ToolItemInGame> tools = new List<ToolItemInGame>();

        /// <summary>
        /// 游戏状态
        /// 0-未开始 1-游戏进行中 2-游戏暂停 3-完成子关卡 4-完成Stage 5-子关卡失败 6-GameOver
        /// </summary>
        int gameStatus = 0;

        public GamePage()
        {
            this.InitializeComponent();
            Instance = this;

            tools.Clear();
            tools.Add(tool1);
            tools.Add(tool2);
            tools.Add(tool3);
            tools.Add(tool4);

            StageManager.Instance.LaunchCount = StageManager.Instance.LaunchCount + 1;

            DisplayProperties.AutoRotationPreferences = DisplayOrientations.Landscape | DisplayOrientations.LandscapeFlipped;
            imgGuide.Tapped += imgGuide_Tapped;

        }

        void imgGuide_Tapped(object sender, TappedRoutedEventArgs e)
        {
            this.imgGuide.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.StartGame();
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            //this.jiuyouAd.Start();
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="pageState">要使用可序列化状态填充的空字典。</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            if (gameStatus == 4 || gameStatus == 6)
            {
                //清除游戏记录
                StageManager.Instance.SavedGameRecord = null;
            }
            else
            {
                SaveGameStaus();
            }
        }

        /// <summary>
        /// 保存进度信息
        /// </summary>
        private void SaveGameStaus()
        {
            SavedGameRecord record = new SavedGameRecord();
            record.CurrentScore = currentScore;
            record.GameMode = StageManager.Instance.CurrentGameMode;
            record.LeftLifeCount = StageManager.Instance.CurrentRestartChange;
            record.LeftSpiritCount = currentSprite;
            record.StageIndex = StageManager.Instance.CurrentStageIndex;
            record.SubStageIndex = StageManager.Instance.CurrentSubStageIndex;
            //道具信息保存
            record.ToolSlotStatus = StageManager.Instance.CurrentToolSlotInfo;
            record.UsedToolStatus = StageManager.Instance.CurrentUsedTool;

            record.Runes = gameCanvas.GetCurrentRuneInfos();

            if (record.Runes != null)
            {
                //设置
                StageManager.Instance.SavedGameRecord = record;
            }

            SaveGameHighlights();
        }

        private void SaveGameHighlights()
        {
            //记录最高分,及保存游戏记录
            if (StageManager.Instance.GameHightlightsRecord.HighScore < currentScore)
            {
                StageManager.Instance.GameHightlightsRecord.HighScore = currentScore;
            }
            StageManager.Instance.SaveGameHightlightsRecord();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (gameStatus == 0)
            {
                bool isNewGame = (bool)e.Parameter;

                if (isNewGame)
                {
                    //从第一个子关卡开始
                    StageManager.Instance.CurrentSubStageIndex = 1;

                    if (StageManager.Instance.CurrentStageIndex == "1" && StageManager.Instance.CurrentGameMode == "e")
                    {
                        this.imgGuide.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    }
                    else
                    {
                        this.imgGuide.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                        StartGame();
                    }
                }
                else
                {
                    //继续上次的游戏
                    LoadLastGame();
                }
            }
        }

        /// <summary>
        /// 载入上次的游戏进度
        /// </summary>
        private void LoadLastGame()
        {
            //动画
            this.gameCanvas.IsHitTestVisible = true;
            //this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(300);
            //this.StoryboardShowGameCanvas.Begin();
            //string uri = uri = "ms-appx:///Images/Tip/start.png";
            //BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
            //imgGamingTip.Source = bitmap;
            //this.StoryboardShowGamingTip.Begin();

            String stageKey = GetCurrentStageKey();

            //获取关卡信息
            if (StageManager.Instance.StageInfos.ContainsKey(stageKey))
            {
                StageInfo stageInfo = StageManager.Instance.StageInfos[stageKey];
                currentStageInfo = stageInfo;

                SavedGameRecord record = StageManager.Instance.SavedGameRecord;
                SetStageInfo(stageInfo);
                toolbar.InitToolBar(stageInfo);
                toolbar.AddScore(record.CurrentScore);
                toolbar.SetLeftSprite(record.LeftSpiritCount);
                currentScore = record.CurrentScore;
                currentSprite = record.LeftSpiritCount;
                currentSumCombo = 0;

                //道具信息保存
                StageManager.Instance.CurrentToolSlotInfo = record.ToolSlotStatus;
                StageManager.Instance.CurrentUsedTool = record.UsedToolStatus;

                //更新生命数量
                UpdateGameRestartChange();

                this.gameCanvas.InitGame(record.Runes);
                gameStatus = 1;

                //判断游戏类型
                JudgeSuccessFail();

                UpdateWaringStatus();

                //更新道具状态
                UpdateToolUI();
                UpdateUsedToolUI();
            }
            else
            {

                //出错
                //返回Stage选择
                //this.NavigationService.Navigate(new Uri("/Pages/StagePage.xaml?Mode=" + StageManager.Instance.CurrentGameMode, UriKind.RelativeOrAbsolute));
            }
        }

        private void StartGame()
        {
            this.gameCanvas.IsHitTestVisible = true;
            //动画
            //this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(300);
            //this.StoryboardShowGameCanvas.Begin();
            //string uri = uri = "ms-appx:///Images/Tip/start.png";
            //BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
            //imgGamingTip.Source = bitmap;
            //this.StoryboardShowGamingTip.Begin();

            String stageKey = GetCurrentStageKey();

            //获取关卡信息
            if (StageManager.Instance.StageInfos.ContainsKey(stageKey))
            {
                StageInfo stageInfo = StageManager.Instance.StageInfos[stageKey];
                currentStageInfo = stageInfo;

                SetStageInfo(stageInfo);
                toolbar.InitToolBar(stageInfo);
                currentScore = 0;
                currentSprite = stageInfo.SpriteCount;
                currentSumCombo = 0;

                this.gameCanvas.InitGame();
                gameStatus = 1;

                UpdateWaringStatus();

                //显示道具情况
                UpdateToolUI();
            }
        }

        public void SetStageInfo(StageInfo stageInfo)
        {
            //更新界面显示
            if (StageManager.Instance.CurrentGameMode == "e")
            {
                this.imgGameModeEasy.Visibility = Windows.UI.Xaml.Visibility.Visible;
                this.imgGameModeHard.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.imgGameModeNormal.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            else if (StageManager.Instance.CurrentGameMode == "n")
            {
                this.imgGameModeEasy.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.imgGameModeHard.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.imgGameModeNormal.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
            else if (StageManager.Instance.CurrentGameMode == "h")
            {
                this.imgGameModeEasy.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.imgGameModeHard.Visibility = Windows.UI.Xaml.Visibility.Visible;
                this.imgGameModeNormal.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            this.txtStageName.Text = stageInfo.StageName;

        }

        /// <summary>
        /// 获取当前关卡Key
        /// </summary>
        /// <returns></returns>
        private string GetCurrentStageKey()
        {
            return StageManager.Instance.CurrentGameMode
                + "_" + StageManager.Instance.CurrentStageIndex
                + "_" + StageManager.Instance.CurrentSubStageIndex;
        }

        /// <summary>
        /// 更新道具状态
        /// </summary>
        internal void UpdateToolUI()
        {
            bool haveTools = false;
            foreach (var slot in StageManager.Instance.CurrentToolSlotInfo.Keys)
            {
                if (StageManager.Instance.CurrentToolSlotInfo[slot] != null)
                {
                    var toolInfo = StageManager.Instance.CurrentToolSlotInfo[slot];
                    //有道具
                    tools[slot].SetTool(toolInfo.Type);
                    tools[slot].SetToolCount(toolInfo.LeftCount);
                    tools[slot].Visibility = Windows.UI.Xaml.Visibility.Visible;
                    haveTools = true;
                }
                else
                {
                    //没有道具
                    tools[slot].Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                }
            }
            if (!haveTools)
            {
                this.txtNoTools.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
            else
            {
                this.txtNoTools.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 更新使用的道具UI
        /// </summary>
        internal void UpdateUsedToolUI()
        {
            toolbar.UpdateUsedToolUI();
        }

        private void UpdateGameRestartChange()
        {
            switch (StageManager.Instance.CurrentRestartChange)
            {
                case 3:
                    this.heart1.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    this.heart3.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    this.heart2.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    break;
                case 2:
                    this.heart1.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    this.heart3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    this.heart2.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    break;
                case 1:
                    this.heart1.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    this.heart3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    this.heart2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    break;
                case 0:
                    this.heart1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    this.heart3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    this.heart2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    break;
            }

        }

        internal void AddScore(int score)
        {
            this.toolbar.AddScore(score);
            currentScore += score;
        }

        internal void AddCombo()
        {
            currentSumCombo++;
        }

        internal void AddSprite(int spriteCount)
        {
            currentSprite += spriteCount;
            this.toolbar.AddSprite(spriteCount);
            UpdateWaringStatus();
        }

        internal void SubSprite()
        {
            currentSprite--;
            this.toolbar.SubSprite(1);
            UpdateWaringStatus();
        }

        private void UpdateWaringStatus()
        {
            if (currentSprite <= 3)
            {
                //显示Waring
                if (this.imageWaring.Visibility == Windows.UI.Xaml.Visibility.Collapsed)
                {
                    this.imageWaring.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    this.StoryboardWaring.RepeatBehavior = RepeatBehavior.Forever;
                    this.StoryboardWaring.Begin();
                }

            }
            else
            {
                //隐藏Waring
                this.imageWaring.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.StoryboardWaring.Stop();
            }
        }

        internal void JudgeSuccessFail()
        {
            if (currentScore >= currentStageInfo.AimScore)
            {
                //关卡成功
                string uri = uri = "ms-appx:///Images/Tip/Complete.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                imgGamingTip.Source = bitmap;
                this.StoryboardShowGamingTip.Begin();
                Win();

            }
            else if (currentSprite <= 0)
            {
                //关卡失败
                string uri = uri = "ms-appx:///Images/Tip/NoSprite.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                imgGamingTip.Source = bitmap;
                this.StoryboardShowGamingTip.Begin();

                Lose();
            }
        }

        private void Lose()
        {
            this.StoryboardHideCanvas.Begin();
            AudioPlayHelper.PlayEffectSound("nosprite");
            //隐藏Waring
            this.imageWaring.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.StoryboardWaring.Stop();
            this.gameCanvas.IsHitTestVisible = false;
            this.StoryboardHideCanvas.BeginTime = TimeSpan.FromMilliseconds(500);
            this.StoryboardHideCanvas.Begin();

            //TODO 扣除一次重试机会
            StageManager.Instance.CurrentRestartChange--;
            UpdateGameRestartChange();
            if (StageManager.Instance.CurrentRestartChange > 0)
            {
                gameStatus = 5;
                //StageClear
                String uri = "ms-appx:///Images/Tip/StageFail.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                ImgStatus.Source = bitmap;

                //按钮状态
                this.btnNext.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.btnRetry.Visibility = Windows.UI.Xaml.Visibility.Visible;
                this.btnReturn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            else
            {
                gameStatus = 6;
                //StageClear
                String uri = "ms-appx:///Images/Tip/GameOver.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                ImgStatus.Source = bitmap;

                //按钮状态
                this.btnNext.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.btnRetry.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.btnReturn.Visibility = Windows.UI.Xaml.Visibility.Visible;

                ////umeng事件
                //UmengSDK.UmengAnalytics.TrackEvent("GameOver", GetCurrentStageKey());
            }
            //显示分数
            ShowScoreG();
            this.StoryboardShowStatus.BeginTime = TimeSpan.FromMilliseconds(1000);
            this.bdrStageStatus.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.StoryboardShowStatus.Begin();
            //隐藏暂停
            this.StoryboardHidePause.Begin();

            SaveGameHighlights();
        }

        private void Win()
        {
            //隐藏Waring
            this.imageWaring.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.StoryboardWaring.Stop();
            this.gameCanvas.IsHitTestVisible = false;
            this.StoryboardHideCanvas.BeginTime = TimeSpan.FromMilliseconds(500);
            this.StoryboardHideCanvas.Begin();

            if (StageManager.Instance.CurrentSubStageIndex == 5)
            {
                AudioPlayHelper.PlayEffectSound("stageclear");
                gameStatus = 4;
                //StageClear
                String uri = "ms-appx:///Images/Tip/StageClear.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                ImgStatus.Source = bitmap;

                //按钮状态
                this.btnNext.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.btnRetry.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.btnReturn.Visibility = Windows.UI.Xaml.Visibility.Visible;

                //解锁后续的Stage
                int currStageIndex = int.Parse(StageManager.Instance.CurrentStageIndex);
                if (currStageIndex < 10)
                {
                    string nextStageKey = StageManager.Instance.CurrentGameMode + "_" + (currStageIndex + 1);
                    if (!StageManager.Instance.StageUnlockStatus.ContainsKey(nextStageKey))
                    {
                        StageManager.Instance.StageUnlockStatus.Add(nextStageKey, true);
                    }
                    StageManager.Instance.StageUnlockStatus[nextStageKey] = true;

                    StageManager.Instance.SaveStageUnlockInfo();
                }

                ////umeng事件
                //UmengSDK.UmengAnalytics.TrackEvent("StageClear", GetCurrentStageKey());

            }
            else
            {
                AudioPlayHelper.PlayEffectSound("levelup");
                gameStatus = 3;
                //StageClear
                String uri = "ms-appx:///Images/Tip/StageSuccess.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                ImgStatus.Source = bitmap;

                //按钮状态
                this.btnNext.Visibility = Windows.UI.Xaml.Visibility.Visible;
                this.btnRetry.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.btnReturn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }

            //显示分数
            ShowScoreG();
            this.StoryboardShowStatus.BeginTime = TimeSpan.FromMilliseconds(1000);
            this.bdrStageStatus.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.StoryboardShowStatus.Begin();
            //隐藏暂停
            this.StoryboardHidePause.Begin();

            SaveGameHighlights();
        }

        private void ShowScoreG()
        {
            this.txtStatusStageName.Text = currentStageInfo.StageName;
            this.txtScore.Text = currentScore.ToString();
            int scoreG = currentScore / 10;
            this.txtScoreG.Text = scoreG.ToString() + " G";
            this.txtCombo.Text = currentSumCombo.ToString();
            int comboG = currentSumCombo * 100;
            this.txtComboG.Text = comboG + " G";

            int sprite = currentSprite;
            int spriteG = currentSprite * 50;

            this.txtSprite.Text = sprite.ToString();
            this.txtSpriteG.Text = spriteG + " G";

            int sumG = comboG + scoreG + spriteG;

            this.txtAddG.Text = "+ " + sumG.ToString() + " G";
            this.txtTotalG.Text = "TOTAL: " + (sumG + StageManager.Instance.TotalG) + " G";
            StageManager.Instance.TotalG += sumG;
        }

        private void btnNext_Click_1(object sender, RoutedEventArgs e)
        {
            AudioPlayHelper.PlayEffectSound("button_click");
            //下一个子关卡
            StageManager.Instance.CurrentSubStageIndex++;
            //再次开始游戏
            StartGame();
            StoryboardHideStatus.Begin();
            StoryboardHidePause.Begin();
            this.StoryboardShowCanvas.Begin();
        }

        private void btnRetry_Click_1(object sender, RoutedEventArgs e)
        {
            AudioPlayHelper.PlayEffectSound("button_click");
            //再试一次
            StartGame();
            StoryboardHideStatus.Begin();
            StoryboardHidePause.Begin();
            this.StoryboardShowCanvas.Begin();
        }

        private async void btnPauseRestart_Click_1(object sender, RoutedEventArgs e)
        {
            AudioPlayHelper.PlayEffectSound("button_click");
            MessageDialog msg = new MessageDialog("确定重新开始吗？如果重新开始将扣除1个生命值。");
            msg.Commands.Add(new UICommand("确定", (command) =>
            {
                AudioPlayHelper.PlayEffectSound("button_click");
                StageManager.Instance.CurrentRestartChange--;
                UpdateGameRestartChange();

                //再试一次
                StartGame();
                StoryboardHideStatus.Begin();
                StoryboardHidePause.Begin();
                this.StoryboardShowCanvas.Begin();
            }));
            msg.Commands.Add(new UICommand("取消", (command) =>
            {
                AudioPlayHelper.PlayEffectSound("button_click");
            }));
            await msg.ShowAsync();
        }

        private void btnReturn_Click_1(object sender, RoutedEventArgs e)
        {
            AudioPlayHelper.PlayEffectSound("button_click");
            //返回两次
            for (int i = 0; i < 2; i++)
            {
                this.GoBack(this, null);
            }
            
        }

        private void btnReturnToMain_Click_1(object sender, RoutedEventArgs e)
        {
            AudioPlayHelper.PlayEffectSound("button_click");
            //返回主菜单
            this.GoHome(this, null);
        }

        private void btnResume_Click_1(object sender, RoutedEventArgs e)
        {
            AudioPlayHelper.PlayEffectSound("button_click");
            if (gameStatus == 2)
            {
                this.StoryboardHidePause.Begin();
                this.StoryboardShowCanvas.Begin();
                gameStatus = 1;
            }
        }

        internal void ReArrange()
        {
            AudioPlayHelper.PlayEffectSound("button_click");
            //做个动画
            this.StoryboardRearrange.Begin();
            gameCanvas.ReArrange();
        }

        internal void CollectAllSpirit()
        {
            gameCanvas.CollectAllSprite();
        }

        internal void CreateNewSpiritRune()
        {
            gameCanvas.CreateNewSpiritRune();
        }

        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
            if (gameStatus == 1)
            {
                AudioPlayHelper.PlayEffectSound("button_click");

                this.StoryboardHideCanvas.Begin();
                this.bdrPause.Visibility = Windows.UI.Xaml.Visibility.Visible;
                this.StoryboardShowPause.Begin();

                //判断是否能够Restart
                if (StageManager.Instance.CurrentRestartChange > 1)
                {
                    this.btnRestart.IsEnabled = true;
                }
                else
                {
                    this.btnRestart.IsEnabled = false;
                }

                gameStatus = 2;
            }
        }

        private async void MokaAd_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Uri uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=903ce9225f");
            await Launcher.LaunchUriAsync(uri);
        }
    }
}
